package heima.com.controller;

import heima.com.domain.Student;
import heima.com.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/studentServlet")
public class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String option = req.getParameter("option");
        if ("login".equals(option)) {
            //登录
            login(req, resp);
        } else if ("findAll".equals(option)) {
            findAll(req, resp);
        }


    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        StudentService service = new StudentService();
        Boolean flag = service.login(name, password);
        if (flag) {
            req.getSession().setAttribute("user", name);
            findAll(req, resp);
        } else {
            try {
                resp.sendRedirect("/login.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        StudentService service = new StudentService();

        List<Student> list = service.findAll(name, password);
        req.getSession().setAttribute("stus", list);
        try {
            req.getRequestDispatcher("/stu/show.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
